package servlet.client;

import dao.domain.Client;
import service.ClientService;
import service.UserService;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;

/**
 * @author gzb
 */
@WebServlet(name = "ClientRechargeServlet", value = "/ClientRechargeServlet")
public class ClientRechargeServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String addAmount = request.getParameter("addAmount");
        System.out.println(addAmount);
        double amount = 0;
        if (addAmount != null) {
            amount = Double.parseDouble(request.getParameter("addAmount"));
        }
        String account = UserService.getAccountFromCookie(request);
        String msg = "{\"msg\":\"fall\"}";
        try {
            Client client = (Client) UserService.selectByAccount("client", account);
            boolean flag = ClientService.recharge(client, amount);
            ClientService.update(client);
            if (flag) {
                msg = "{\"msg\":\"success\"}";
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        response.getWriter().write(msg);
        System.out.println("finish");
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        System.out.println("ClientRechargeServlet现在来了一个post请求，将要去走get的代码了。");
        doGet(request, response);
    }
}
